<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UpdateUserBalanceJob implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $userId;
    protected $amount;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $amount)
    {
        $this->userId = $userId;
        $this->amount = $amount;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 更新用户余额
        User::query()->where('id', $this->userId)->increment('balance', $this->amount);
    }

    public function failed(\Throwable $exception)
    {
        logger()->error('用户余额更新失败', [
            'userId' => $this->userId,
            'balance' => $this->amount,
            'exception' => $exception
        ]);
    }
}
